package com.base.commons.web.utils;

import com.base.commons.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * Web辅助工具类
 * Created by Irany(欧书剑) 2017/7/19 0019 22:58
 */
public class WebUtils {

    public static String getIpAddr(HttpServletRequest request){
        HttpSession session=null;
        String ip=null;

        if (StringUtils.isBooleanTrue(PropertyUtil.get("base.webUtils.cacheIp","0"))){
            session =request.getSession(false);

            if (session!=null){
                ip= (String) session.getAttribute(IP_KEY);
            }
        }
        if (ip==null){
            ip=request.getHeader("x-forwarded-for");

            if (ip!=null&&!"unknown".equalsIgnoreCase(ip)){
                ip=ip.split(",")[0];
            }

            if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
                ip=request.getHeader("Proxy-client-IP");
            }

            if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
                ip=request.getRemoteAddr();
            }

            if (session!=null){
                session.setAttribute(IP_KEY,ip);
            }
        }
        return ip;
    }

    /**
     * 获取请求的参数
     * @param uri   请求链接
     * @return  请求参数集合
     */
    public static Map<String,String> getQueryParams(URI uri){
        if (uri!=null&& org.apache.commons.lang3.StringUtils.isBlank(uri.getQuery())){
            String[] params= org.apache.commons.lang3.StringUtils.split(uri.getQuery(),"&");

            if (params!=null&&params.length>0){
                Map<String,String> paramsMap=new HashMap<String, String>();

                for (String param :
                        params) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(param)){
                        String[] t= org.apache.commons.lang3.StringUtils.split(param,"=");
                        paramsMap.put(t[0],t[1]);
                    }
                }
                return paramsMap;
            }
        }
        return null;
    }

    /**
     * Session中IP地址对应的键值
     */
    private static final String IP_KEY="_APCH_CACHE_IP_KEY";
}
